package portal.pubcontroller.system;

import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import nc.vo.pub.BusinessException;
import net.sf.json.JSONObject;
import portal.pub.util.pf.JsonObjectUtil;
import portal.pub.util.pf.Result;
import portal.pubitf.system.pf.IUserService;
import portal.pubvo.system.UserVo;

@Controller
@SuppressWarnings("all")
public class UserController {

	@Resource(name = "userServiceImpl")
	private IUserService userService;

	//登录
	@RequestMapping(value = "/login")
	public void login(String phone,String password,String sms,HttpSession httpSession,HttpServletResponse response,String type) {
		response.setContentType("text/html;charset=utf-8");
		JSONObject json = new JSONObject();
		try {
			// 登录
			String result = userService.getAllByWhere(phone);
			Result res = (Result) JsonObjectUtil.parJsonToObject(result, new Result());

			//是否有该用户
			if(res.getStatus().equals("1")) {
				json.put("status", res.getStatus());
				throw new BusinessException(res.getMessage());
			}
			//获取用户信息
			UserVo user = res.getUser();
			if(type.equals("0")) {	//密码登录
				String md5 = "U_U++--V" + DigestUtils.md5Hex(phone + StringUtils.stripToEmpty(password));
				if (!md5.equals(user.getPassword())) {
					json.put("status", "1");
					throw new BusinessException("密码错误啦，请重新输入。");
				}
			}else {					//验证码登录
				//获取随机生成的验证码
				String yzm = "";
				if(!sms.equals(yzm)) {
					json.put("status", "1");
					throw new BusinessException("验证码错误，请重新输入。");
				}
			}
			/*if (user.getApproval_state() == 1) {
				json.put("status", "1");
				throw new BusinessException("该账号在审核中，请等待。。。");
			}*/
			if (user.getApproval_state() == 2) {
				json.put("status", "1");
				throw new BusinessException("该账号审核不通过，原因：" + user.getApproval_opinion() + "，请联系管理员。");
			}
			//登录成功
			json.put("status", "0");
			json.put("message", "登录成功");
			httpSession.setAttribute("user", user);
		} catch (Exception e) {
			json.put("status", "1");
			json.put("message", "1111111");
		}finally {
			try {
				response.getWriter().println(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	//校验
	@RequestMapping(value = "/userCheck")
	public void userCheck(HttpServletRequest request, HttpServletResponse response, String phone) throws BusinessException {
		try {
			//查询是否有该账号
			String result = userService.getAllByWhere(phone);
			Result res = (Result) JsonObjectUtil.parJsonToObject(result, new Result());

			//结果返回
			response.setContentType("text/html;charset=utf-8");
			JSONObject json = new JSONObject();
			json.put("status", res.getStatus());
			json.put("message", res.getMessage());
			response.getWriter().println(json);
		} catch (Exception e) {
			e.getStackTrace();
		}
	}

	//短信验证码
	@RequestMapping(value = "/sms")
	public void sms(HttpServletRequest request, HttpServletResponse response, String phone) {
		try {
			//结果返回
			response.setContentType("text/html;charset=utf-8");
			JSONObject json = new JSONObject();
			json.put("status", "0");
			json.put("message", "成功");
			response.getWriter().println(json);
		} catch (Exception e) {
			e.getStackTrace();
		}
	}

	//注册
	@RequestMapping(value = "/register")
	public void register(HttpServletRequest request, HttpServletResponse response, String phone,String password,String sms) {
		response.setContentType("text/html;charset=utf-8");
		JSONObject json = new JSONObject();
		try {
			UserVo vo = new UserVo();
			vo.setId(UUID.randomUUID().toString());
			vo.setPhone(phone);
			vo.setPk_role("49595fe1-ca35-48d9-8e00-ef3b0910c686");
			String md5 = "U_U++--V" + DigestUtils.md5Hex(phone + StringUtils.stripToEmpty(password));
			vo.setPassword(md5);
			//添加
			int insert = userService.insert(vo);
			if(insert==0) {
				json.put("status", "1");
				throw new BusinessException("注册失败。");
			}
			json.put("status", "0");
			json.put("message", "注册成功");
		} catch (Exception e) {
			json.put("status", "1");
			json.put("message", e.getMessage());
		}finally {
			try {
				response.getWriter().println(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	



	//操作(关闭/发布/审核/需审核)
	/*@RequestMapping(value = "/operation")
	public ModelAndView operation(String id,String sta,HttpServletRequest req,HttpServletResponse res) {
		ModelAndView mv = new ModelAndView();
		try {
			//查询
			Reptile vo = reptileService.getById(id);
			if(sta.equals("1")||sta.equals("0")) {
				vo.setState(sta);
			}else if(sta.equals("4")) {
				vo.setState("0");
				vo.setType_state("0");
			}else if(sta.equals("5")) {
				vo.setState("1");
				vo.setType_state("1");
			}
			vo.setTs(DateUtil.getDateAtYMDHMS());
			reptileService.update(vo);
			mv.setViewName("redirect:/manage.do");
		} catch (Exception e) {
			mv.setViewName("error");
			e.printStackTrace();
		}
		return mv;
	}


	//操作(批量关闭/发布)
	@RequestMapping(value = "/batchOperation")
	public void batchOperation(String[] ids,String sta,HttpServletRequest req,HttpServletResponse res) {
		try {
			int fb = 0;int gb = 0;
			for (int i = 0; i < ids.length; i++) {
				Reptile vo = reptileService.getById(ids[i]);
				if(sta.equals("0")&&vo.getState().equals("1")){
					vo.setState(sta);
					vo.setTs(DateUtil.getDateAtYMDHMS());
					reptileService.update(vo);
					fb++;
				}else if(sta.equals("1")&&vo.getState().equals("0")){
					vo.setState(sta);
					vo.setTs(DateUtil.getDateAtYMDHMS());
					reptileService.update(vo);
					gb++;
				}
			}
			res.setCharacterEncoding("utf-8");
			PrintWriter out = res.getWriter();
			out.print(sta.equals("0")?fb>0?"批量发布成功":"未勾选发布的数据":gb>0?"批量关闭成功":"未勾选关闭的数据");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//操作(批量审核/需审核)
	@RequestMapping(value = "/batchReview")
	public void batchReview(String[] ids,String sta,HttpServletRequest req,HttpServletResponse res) {
		try {
			int fb = 0;int gb = 0;
			for (int i = 0; i < ids.length; i++) {
				Reptile vo = reptileService.getById(ids[i]);
				if(sta.equals("4")&&vo.getType_state().equals("1")){
					vo.setState("0");
					vo.setType_state("0");
					vo.setTs(DateUtil.getDateAtYMDHMS());
					reptileService.update(vo);
					fb++;
				}else if(sta.equals("5")&&vo.getType_state().equals("0")){
					vo.setState("1");
					vo.setType_state("1");
					vo.setTs(DateUtil.getDateAtYMDHMS());
					reptileService.update(vo);
					gb++;
				}
			}
			res.setCharacterEncoding("utf-8");
			PrintWriter out = res.getWriter();
			out.print(sta.equals("4")?fb>0?"批量审核通过":"未勾选审核通过的数据":gb>0?"批量需审核成功":"未勾选需审核的数据");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	//管理页面
	@RequestMapping(value = "/manage")
	public ModelAndView manage(HttpServletRequest req,HttpServletResponse res) {
		ModelAndView mv = new ModelAndView();
		try {
			//分页
			int dqy = 1;int xsts = 25;
			Map<String, Object> map = new HashMap<String,Object>();
			String index = req.getParameter("index");
			String size = req.getParameter("size");
			if(index!=null)dqy = Integer.valueOf(index);
			if(size!=null)xsts = Integer.valueOf(size);
			//参数

			String title = req.getParameter("title");
			if(title!=null&&title!="") {
				title = new String(req.getParameter("title").getBytes("ISO-8859-1"),"UTF-8");
				map.put("title", title);
			}

			String begin_date = req.getParameter("begin_date");
			if(begin_date!=null&&begin_date!="") {
				map.put("begin_date", begin_date);
			}

			String end_date = req.getParameter("end_date");
			if(end_date!=null&&end_date!="") {
				map.put("end_date", end_date);
			}

			String state = req.getParameter("state");
			if(state==null)state="2";
			if(!state.equals("2")) {
				map.put("state", state);
			}

			String type_state = req.getParameter("type_state");
			if(type_state==null)type_state="2";
			if(!type_state.equals("2")) {
				map.put("type_state", type_state);
			}

			String pk_reptileclass = req.getParameter("pk_reptileclass");
			if(pk_reptileclass==null)pk_reptileclass="0";
			if(!pk_reptileclass.equals("0")) {
				map.put("pk_reptileclass", pk_reptileclass);
			}

			map.put("index", dqy);
			map.put("pagesize", xsts);

			//查询全部分类
			List<ReptileClass> rcs = reptileClassService.getAll();
			mv.addObject("class_list", rcs);

			//查询新闻信息
			List<Reptile> list = reptileService.getPagesByWhere(map);
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setDate(DateUtil.getDateAtYMD());
			}
			//查询总条数
			Integer count = reptileService.getPagesTotalByWhere(map);
			int pages=count%xsts==0?count/xsts:count/xsts+1;

			mv.addObject("list", list);
			mv.addObject("index", dqy);
			mv.addObject("pages", pages);
			mv.addObject("count", count);
			mv.addObject("size", xsts);

			//条件
			mv.addObject("title", title);
			mv.addObject("begin_date", begin_date);
			mv.addObject("end_date", end_date);
			mv.addObject("zt", state);
			mv.addObject("type_state", type_state);
			mv.setViewName("manage");
		} catch (Exception e) {
			mv.setViewName("error");
			e.printStackTrace();
		}
		return mv;
	}

	//前端查询全部
	@RequestMapping(value = "/clientData")
	public void clientData(HttpServletRequest req,HttpServletResponse res) {
		try {
			// 数据返回
			List<Reptile> lists = reptileService.getClientAll();
			res.setCharacterEncoding("utf-8");
			PrintWriter out = res.getWriter();
			out.print(JsonObjectUtil.objectTojson(lists));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
}
